# -*- coding: utf-8 -*-
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# Odoo Connector
# QQ:35350428
# 邮件:sale@100china.cn
# 手机：13584935775
# 作者：wangguangjian
# 公司网址： www.odoo.pw  www.100china.cn
# Copyright 昆山一百计算机有限公司 2012-2016 Amos
# 日期：15/5/27
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

import logging
from datetime import datetime
from odoo import api, fields, models, tools, SUPERUSER_ID, _
from odoo.exceptions import AccessDenied, AccessError, UserError, ValidationError
from odoo.osv import expression
from jinja2 import Environment, FileSystemLoader
import os, os.path
import shutil
import sys, os, stat
import random
import string

_logger = logging.getLogger(__name__)
import sys

reload(sys)
sys.setdefaultencoding('utf8')


class res_groups(models.Model):
    _inherit = "res.groups"

    @api.multi
    def make_security(self):
        '''
        根据职务生成对应的全部权限组
        :param cr:
        :param uid:
        :param ids:
        :param context:
        :return:
        '''
        o = self

        # 生成文件夹
        # 复制当前所有文件到指定文件 再读取模板然后更新再更新文件
        source = ''
        target = ''

        seed = "1234567890abcdefghijklmnopqrstuvwxyz"
        salt = ''.join(random.sample(string.ascii_letters + string.digits, 8))

        #::::如果是字段权限名称固定
        file_name = ''
        if self.is_fields:
            file_name = self.filename
        else:
            file_name = 'amos_access_' + salt

        if self.is_fields!=True:
            file_count = self.env['ir.module.module'].sudo().search_count([('name', '=', file_name)])
            if file_count > 0:
                raise UserError(u'文件夹已存在,请删除后再生成，或改一个名称!')

        sysstr = sys.platform
        if sysstr.startswith('win32'):
            source = os.path.dirname(os.path.dirname(__file__)) + '/templates/default'
            # 目标文件路径
            target = os.path.dirname(os.path.dirname(__file__)).replace('Amos_Groups_Tools',
                                                                        '') + '%s' % (file_name)
        elif (sysstr.startswith('linux')):
            source = os.path.dirname(os.path.dirname(__file__)) + '/templates/default'
            # 目标文件路径
            target = os.path.dirname(os.path.dirname(__file__)).replace('Amos_Groups_Tools',
                                                                        '') + '%s' % (file_name)
        elif (sysstr.startswith('darwin')):
            """MAC"""
            source = os.path.split(os.path.realpath(__file__))[0].replace('/module', '') + '/templates/default'
            # 目标文件路径
            target = os.path.split(os.path.realpath(__file__))[0].replace('/Amos_Groups_Tools/module',
                                                                          '') + '/%s' % (file_name)
        else:
            print (u"未知的操作系统")

        if os.path.exists(target) == False:
            os.makedirs(target)
        self.copyfile(source, target)

        templateLoader = FileSystemLoader(searchpath=target)
        env = Environment(loader=templateLoader)

        #:::所有依赖
        depends_arr = []
        for model in o.model_access:
            for name in model.model_id.modules.split(','):
                if str(name.replace(' ', '')) not in depends_arr:
                    depends_arr.append(str(name.replace(' ', '')))

        #:::::::::::::::创建__openerp__
        filename = '__manifest__.py'
        template = env.get_template(filename)

        depends = str(depends_arr).replace(' ', '')

        model_name = o.authority_id.name or o.name
        if o.is_fields:
            model_name = u'字段权限组'
            depends = ['base','Amos_Groups_Tools']

        copyright = u"""
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# Odoo Connector
# QQ:35350428
# 邮件:sale@100china.cn
# 手机：13584935775
# 作者：'odoo'
# 公司网址： www.odoo.pw  www.100china.cn
# Copyright 昆山一百计算机有限公司 2012-2016 Amos
# 日期：%s
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
        """ % datetime.now()
        value = {
            'name': model_name,
            'depends': depends,
            'copyright': copyright,
        }
        html = template.render(object=value)
        f = file(target + '/' + filename, 'w')
        f.truncate()
        f.write(html)

        #:::::::::::::::创建规则

        ir_rule = ''
        if o.is_fields:
            #:::::::::::::::有多少个这样的组

            res_groups = ''
            groups = self.env['res.groups'].search([('is_fields', '=', True)])


            for line in groups:
                res_groups += """
        <record id="fields_groups_%s_%s" model="res.groups">
            <field name="name">%s</field>
            <field name="category_id" ref="Amos_Groups_Tools.amos_module_field"/>
        </record>
                """ % ((o.fields_name.model_id.model).replace('.','_'),o.fields_name.name,line.name)

            filename = 'security/security.xml'
            template = env.get_template(filename)
            value = {
                'res_groups': res_groups,
                'ir_rule': '',
                'ir_ui_menu': '',
            }
            html = template.render(object=value)
            f = file(target + '/' + filename, 'w')
            f.truncate()
            f.write(html)

            #:::::::::::::::创建ir.model.access.csv
            filename = 'security/ir.model.access.csv'
            template = env.get_template(filename)
            value = {
                'ir_model_access': '',
            }
            html = template.render(object=value)
            f = file(target + '/' + 'security/ir.model.access.csv', 'w')
            f.truncate()
            f.write(html)

            #:::::::::::::::创建依赖对象引用
            filename = 'models.py'
            template = env.get_template(filename)
            value = {
                'class_model': '',
            }
            html = template.render(object=value)
            f = file(target + '/' + 'models.py', 'w')
            f.truncate()
            f.write(html)

        else:

            for rule in o.rule_groups:
                ir_rule += """
                <record id="%s_%s_rule" model="ir.rule">
                    <field name="name">%s</field>
                    <field ref="model_%s" name="model_id"/>
                    <field name="domain_force">%s</field>
                    <field name="groups" eval="[(4, ref('%s'))]"/>
                </record>
    
                """ % (rule.model_id.model.replace('.', '_'), o.authority_id.value, o.authority_id.name,
                       rule.model_id.model.replace('.', '_'), rule.domain_force,
                       file_name + '.' + 'amos_access_' + o.authority_id.value)

            #:::::::::::::::创建菜单
            ir_ui_menu = ''
            for menu in o.menu_access:
                o_menu = self.env['ir.model.data'].search_read([('res_id', '=', menu.id),
                                                                ('model', '=', 'ir.ui.menu')],
                                                               ['name', 'module'])
                ir_ui_menu += """
                <record model="ir.ui.menu" id="%s.%s">
                    <field eval="[(4, ref('%s'))]" name="groups_id"/>
                </record>
                """ % (o_menu[0]['module'], o_menu[0]['name'],
                       file_name + '.' + 'amos_access_' + o.authority_id.value)

            #:::::::::::::::创建权限
            res_groups = """
                <record id="amos_access_%s" model="res.groups">
                    <field name="name">%s</field>
                    <field name="category_id" ref="Amos_Groups_Tools.amos_module_pop"/>
                </record>
            """ % (o.authority_id.value, o.authority_id.name)

            filename = 'security/security.xml'
            template = env.get_template(filename)
            value = {
                'res_groups': res_groups,
                'ir_rule': ir_rule,
                'ir_ui_menu': ir_ui_menu,
            }
            html = template.render(object=value)
            f = file(target + '/' + filename, 'w')
            f.truncate()
            f.write(html)

            #:::::::::::::::创建ir.model.access.csv
            filename = 'security/ir.model.access.csv'
            template = env.get_template(filename)

            ir_model_access = ''
            for acc in o.model_access:
                ir_model_access += '''
    access_%s_%s,%s.%s,%s.model_%s,%s.%s,%s,%s,%s,%s''' % (
                    acc.model_id.model.replace('.', '_'), o.authority_id.value, acc.model_id.model, o.authority_id.value,
                    acc.model_id.modules.split(',')[0].replace(' ', ''), acc.model_id.model.replace('.', '_'),
                    file_name,
                    'amos_access_' + o.authority_id.value, acc.perm_read, acc.perm_write, acc.perm_create, acc.perm_unlink)

            value = {
                'ir_model_access': ir_model_access,
            }
            html = template.render(object=value)
            f = file(target + '/' + filename, 'w')
            f.truncate()
            f.write(html)

            #:::::::::::::::创建依赖对象引用

            class_model = ''
            depends_model = []
            for rule in o.rule_groups:
                if str(rule.model_id.model) not in depends_model:
                    depends_model.append(str(rule.model_id.model))
                    class_model += '''
    
    class %s_%s(models.Model):
        _inherit = "%s"
                        ''' % (rule.model_id.model.replace('.', '_'), o.authority_id.value, rule.model_id.model)

            filename = 'models.py'
            template = env.get_template(filename)
            value = {
                'class_model': class_model,
            }
            html = template.render(object=value)
            f = file(target + '/' + filename, 'w')
            f.truncate()
            f.write(html)

        return True

    def copyfile(self, src, dst, symlinks=False):
        names = os.listdir(src)
        if not os.path.isdir(dst):
            os.makedirs(dst)
        errors = []
        for name in names:
            srcname = os.path.join(src, name)
            dstname = os.path.join(dst, name)
            try:
                if symlinks and os.path.islink(srcname):
                    linkto = os.readlink(srcname)
                    os.symlink(linkto, dstname)
                elif os.path.isdir(srcname):
                    self.copyfile(srcname, dstname, symlinks)
                else:
                    if os.path.isdir(dstname):
                        os.rmdir(dstname)
                    elif os.path.isfile(dstname):
                        os.remove(dstname)
                    shutil.copy2(srcname, dstname)
            except (IOError, os.error) as why:
                errors.append((srcname, dstname, str(why)))
            except OSError as err:
                errors.extend(err.args[0])
